package com.share.config.amazon.s3;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.share.common.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

@Service
public class AmazonS3Service {

    @Value("${amazon.s3.bucketName}")
    private String bucket;

    @Value("${amazon.s3.httpsDomain}")
    private String domain;

    @Autowired
    private AmazonS3 client;

    public String upload(byte[] input, String tmpFileName) {
        ByteArrayInputStream bis = new ByteArrayInputStream(input);
        String upload = upload(bis, tmpFileName);
        return upload;
    }

    /**
     * 文件流执行文件上传
     *
     * @param input
     * @param tmpFileName
     * @return
     * @throws IOException
     */
    public String upload(InputStream input, String tmpFileName) {
        String fileSuffix = "";
        int i = tmpFileName.lastIndexOf(".");
        if (i >= 0) {
            fileSuffix = tmpFileName.substring(i);
        }
        String remoteFilePath = UUIDUtil.genFileName() + fileSuffix;
        ObjectMetadata metadata = new ObjectMetadata();
        client.putObject(new PutObjectRequest(bucket, remoteFilePath, input, metadata).withCannedAcl(CannedAccessControlList.PublicRead));
        String url = domain + "/" + bucket + "/" + remoteFilePath;
        return url;
    }
}
